package com.ny.dao.impl;

import com.ny.dao.StudentDao;
import com.ny.entity.Student;
import com.ny.until.DbUntil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class StudentDaoImpl implements StudentDao {
    private DbUntil dbUntil = new DbUntil();
    @Override
    public Student login(String name, String password) throws Exception {
        Connection con = dbUntil.getCon();
        String sql = "select * from students where name = ? and password = ?";
        PreparedStatement preparedStatement = con.prepareStatement(sql);
        preparedStatement.setString(1, name);
        preparedStatement.setString(2, password);
        ResultSet resultSet = preparedStatement.executeQuery();
        Student student = new Student();
        if (resultSet.next()){
            int id  = resultSet.getInt("student_id");
            String sname = resultSet.getString("name");
            String phone = resultSet.getString("phone");
            String spassword = resultSet.getString("password");
            student.setStudentId(id);
            student.setName(sname);
            student.setPhone(phone);
            student.setPassword(spassword);
            return student;
        }
        return null;
    }

    @Override
    public int insertStudent(Student student) throws SQLException, ClassNotFoundException {
        Connection con = dbUntil.getCon();
        String sql = "insert into students(name,phone,password) values(?,?,?)";
        PreparedStatement preparedStatement = con.prepareStatement(sql);
        preparedStatement.setString(1, student.getName());
        preparedStatement.setString(2, student.getPhone());
        preparedStatement.setString(3, student.getPassword());
        int rows = preparedStatement.executeUpdate();
        return rows;
    }
}
